<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工首页</title>
    <link rel="stylesheet" href="../../../css/style.css">

    <!-- 引入 jQuery-->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 引入 Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>


    <style>
        .submenu { display: none; }
        .menu-item.active > .submenu { display: block; }
        .menu-arrow { transition: transform 0.2s; }
        .menu-item.active > a > .menu-arrow { transform: rotate(90deg); }
        .menu-list > .menu-item.active > a {
            color: #28a745;
            font-weight: bold;
        }
        .submenu li a.active { color: #28a745; font-weight: bold; transform: translateY(2px); display: inline-block; }
        .page-title { font-size: 22px; font-weight: 600; margin-bottom: 20px; color: #333; display: flex; align-items: center; gap: 10px; }
        .content-wrapper { padding: 20px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }

        /* 布局样式 */
        .row { display: flex; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; }
        .col-md-8, .col-md-4 { position: relative; width: 100%; padding-right: 15px; padding-left: 15px; }
        @media (min-width: 768px) {
            .col-md-8 { flex: 0 0 66.666667%; max-width: 66.666667%; }
            .col-md-4 { flex: 0 0 33.333333%; max-width: 33.333333%; }
        }

        /* 消息列表区域样式 */
        .message-list-area {
            margin-top: 15px;
            padding: 12px;
            border: 1px solid #eee;
            border-radius: 5px;
            background-color: #f9f9f9;
            min-height: 300px;
            display: flex;
            flex-direction: column;
        }

        /* 消息卡片样式 */
        .message-card {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 12px;
            margin-bottom: 8px;
            background-color: #fff;
            cursor: pointer;
            transition: box-shadow 0.2s ease-in-out, transform 0.2s ease-in-out;
            position: relative;
        }

        .message-card:hover {
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transform: translateY(-1px);
        }

        .message-card h5 {
            margin: 0 0 8px 0;
            color: #dc3545;
            font-size: 14px;
            font-weight: 600;
            padding-right: 60px;
        }

        .message-card p {
            margin: 0 0 4px 0;
            font-size: 13px;
            color: #666;
            line-height: 1.4;
        }

        .message-card strong {
            color: #333;
            font-weight: 500;
            display: inline-block;
            min-width: 70px;
            font-size: 13px;
        }

        .message-status {
            position: absolute;
            top: 12px;
            right: 12px;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: 500;
            background-color: #dc3545;
            color: white;
            line-height: 1.4;
        }

        /* 消息类型筛选样式 */
        .search-item {
            margin-bottom: 12px;
        }

        .search-label {
            display: block;
            margin-bottom: 4px;
            font-size: 13px;
            color: #555;
            font-weight: 500;
        }

        .form-select-sm {
            height: 32px;
            padding: 4px 8px;
            font-size: 13px;
            border-radius: 4px;
            border: 1px solid #ddd;
            width: 100%;
            max-width: 180px;
        }

        /* 消息卡片容器样式 */
        #message-cards-container {
            flex-grow: 1;
            overflow-y: auto;
            padding-right: 4px;
            margin-top: 8px;
            max-height: calc(100vh - 300px);
        }

        /* 空消息提示样式 */
        #message-cards-container p {
            text-align: center;
            color: #666;
            font-size: 13px;
            margin-top: 15px;
        }

        /* 修改排班表列宽 */
        @media (min-width: 768px) {
            .schedule-section {
                flex: 0 0 55% !important;
                max-width: 55% !important;
            }
            .plan-section {
                flex: 0 0 25% !important;
                max-width: 25% !important;
            }
            .notification-section {
                flex: 0 0 20% !important;
                max-width: 20% !important;
            }
        }

        .report-area { 
            margin-top: 15px; 
            padding: 15px; 
            border: 1px solid #eee; 
            border-radius: 5px; 
            background-color: #f9f9f9; 
            min-height: 300px; 
        }

        /* 排班表容器样式 */
        .schedule-container {
            width: 100%;
            overflow-x: auto;
            padding-bottom: 10px; /* 为滚动条预留空间 */
        }

        /* 排班表样式 */
        .schedule-table {
            min-width: 800px; /* 减小整体最小宽度 */
            width: 100%;
            border-collapse: collapse;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        /* 自定义滚动条样式 */
        .schedule-container::-webkit-scrollbar {
            height: 8px;
            width: 8px;
        }

        .schedule-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        .schedule-container::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        .schedule-container::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        /* 表格单元格样式优化 */
        .schedule-table td {
            min-width: 100px; /* 进一步减小单元格最小宽度 */
            height: 110px; /* 稍微减小高度 */
            padding: 6px; /* 减小内边距 */
            vertical-align: top;
            border: 1px solid #ddd;
        }

        .schedule-table th {
            min-width: 100px; /* 与td保持一致 */
            padding: 10px 6px;
            background-color: #f2f2f2;
            border: 1px solid #ddd;
            text-align: center;
            font-weight: bold;
        }

        /* 使主内容区域填充纵向空间 */
        .admin-main {
            display: flex;
            flex-direction: column;
            flex-grow: 1;
        }

        
        .content-wrapper {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        .content-wrapper .row {
             flex-grow: 1;
        }

        .content-wrapper .row > div {
            display: flex;
            flex-direction: column;
        }

        .report-area {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        /* 排班表样式 */
        .filter-container {
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .filter-item {
            display: flex;
            align-items: center;
        }

        .filter-item label {
            margin-right: 10px;
            font-weight: bold;
        }

        .filter-item select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-width: 150px;
        }

        .schedule-table td.empty {
            background-color: #f9f9f9;
        }

        .schedule-table .date {
            font-weight: bold;
            margin-bottom: 5px;
            text-align: right;
        }

        .schedule-table .content {
            font-size: 12px;
            text-align: left;
        }

        /* 排班信息样式优化 */
        .schedule-entry {
            margin-bottom: 6px;
            padding: 4px;
            border-radius: 3px;
            background-color: #e6f7ff;
            border-left: 3px solid var(--primary-color);
            font-size: 11px;
            line-height: 1.3;
        }

        .schedule-entry .shift-type {
            font-weight: bold;
            color: #1890ff;
            display: block;
            font-size: 12px;
        }

        .schedule-entry .department {
            color: #666;
            font-size: 10px;
            display: block;
            margin-top: 1px;
        }

        .schedule-entry .shift-time {
            color: #333;
            font-size: 10px;
            display: block;
            margin-top: 1px;
        }

        .inactive-entry {
            background-color: #ffe6e6;
            border-left: 3px solid #ff4d4f;
            opacity: 0.7;
        }

        .inactive-entry .shift-type {
            color: #ff4d4f;
            text-decoration: line-through;
        }

        .btn-refresh {
            padding: 8px 16px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-refresh:hover {
            opacity: 0.9;
        }

        /* iOS风格模态框样式 */
        .ios-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.4);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1050;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .ios-modal.show {
            display: flex;
            opacity: 1;
        }

        .ios-modal-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 0;
            max-width: 400px;
            width: 90%;
            max-height: 80vh;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            transform: scale(0.8);
            transition: transform 0.3s ease;
        }

        .ios-modal.show .ios-modal-content {
            transform: scale(1);
        }

        .ios-modal-header {
            padding: 20px 20px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }

        .ios-modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .ios-modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .ios-detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .ios-detail-item:last-child {
            border-bottom: none;
        }

        .ios-detail-label {
            font-weight: 500;
            color: #666;
            font-size: 14px;
        }

        .ios-detail-value {
            font-weight: 400;
            color: #333;
            font-size: 14px;
            text-align: right;
            max-width: 60%;
            word-wrap: break-word;
        }

        .ios-modal-footer {
            padding: 15px 20px 20px;
            text-align: center;
            display: flex;
            justify-content: space-between;
            gap: 10px;
        }

        .ios-btn {
            flex: 1;
            border: none;
            border-radius: 12px;
            padding: 12px 20px;
            font-size: 15px;
            font-weight: 500;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .ios-btn-primary {
            background: #007AFF;
            color: white;
        }

        .ios-btn-primary:hover {
            background: #0056CC;
        }

        .ios-btn-danger {
            background: #ff3b30;
            color: white;
        }

        .ios-btn-danger:hover {
            background: #dc3545;
        }

        /* 滚动条样式 */
        .ios-modal-body::-webkit-scrollbar {
            width: 4px;
        }

        .ios-modal-body::-webkit-scrollbar-track {
            background: transparent;
        }

        .ios-modal-body::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }

        /* 表单样式 */
        .ios-form-group {
            margin-bottom: 15px;
        }

        .ios-form-label {
            display: block;
            margin-bottom: 8px;
            color: #666;
            font-size: 14px;
            font-weight: 500;
        }

        .ios-form-control {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 10px;
            font-size: 14px;
            color: #333;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.2s ease;
        }

        .ios-form-control:focus {
            outline: none;
            border-color: #007AFF;
            box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
        }

        .ios-form-control::placeholder {
            color: #999;
        }

        /* 页面切换按钮样式 */
        .page-switch-container {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .page-switch-btn {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background: #f8f9fa;
            color: #333;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .page-switch-btn.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }

        .page-switch-btn:hover {
            background: #e9ecef;
        }

        .page-switch-btn.active:hover {
            background: var(--primary-color);
            opacity: 0.9;
        }

        /* 请假申请表单样式 */
        .leave-form {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .form-row {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 15px;
        }

        .form-group {
            flex: 1;
            min-width: 200px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }

        .form-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }

        .btn-container {
            text-align: center;
            margin-top: 20px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s ease;
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            opacity: 0.9;
        }

        /* 请假记录表格样式 */
        .leave-table {
            width: 100%;
            border-collapse: collapse;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-top: 20px;
        }

        .leave-table th,
        .leave-table td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
        }

        .leave-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        .leave-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .status-pending {
            color: #faad14;
            font-weight: bold;
        }

        .status-approved {
            color: #52c41a;
            font-weight: bold;
        }

        .status-rejected {
            color: #f5222d;
            font-weight: bold;
        }

        /* 员工信息卡片 */
        .employee-card {
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
        }

        .employee-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background-color: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: bold;
            color: var(--primary-color);
            margin-right: 20px;
        }

        .employee-info {
            flex: 1;
        }

        .employee-name {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .employee-details {
            display: flex;
            gap: 20px;
            color: #666;
            font-size: 14px;
        }

        .employee-detail-item {
            display: flex;
            align-items: center;
        }

        .employee-detail-label {
            font-weight: bold;
            margin-right: 5px;
        }

        .result-message {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            display: none;
        }

        .success-message {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 隐藏页面内容 */
        .page-content {
            display: none;
        }

        .page-content.active {
            display: block;
        }
        /* 请假申请样式 */

    </style>
</head>
<body>
    <div class="admin-layout">
        <!-- 顶部导航栏 -->
        <header class="admin-header">
            <div class="header-left">
                <div class="logo">生产过程管理系统</div>
            </div>
            <div class="header-right">
                <span class="user-info">员工</span>
                <span class="user-name"><script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script></span>
                <button class="logout-btn" onclick="logout()">退出</button>
            </div>
        </header>
        <!-- 左侧菜单 -->
        <aside class="admin-sidebar">
            <ul class="menu-list">
                <li class="menu-item">
                    <a href="employee_home.html">
                        <span class="menu-icon">🏠</span>
                        <span class="menu-title">首页</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">📦</span>
                        <span class="menu-title">物料管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../material/material_list.html">物料列表</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">⚙️</span>
                        <span class="menu-title">设备管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../device/device_list.html">设备列表</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">📝</span>
                        <span class="menu-title">产品管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../product/product_plan_list.html">查看生产计划</a></li>
                        <li><a href="../product/product_plan_commit.html">提交完成情况</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">🏢</span> 
                        <span class="menu-title">供应商管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../provider/provider_list.html">供应商列表</a></li>
                    </ul>
                </li>
            </ul>
        </aside>
        <!-- 主内容区域 -->
        <main class="admin-main">
            <div class="content-wrapper">
                <div class="row">
                    <!-- 左侧排班表/请假申请切换区域 -->
                    <div class="col-md-4 schedule-section">
                        <!-- 页面切换按钮 -->
                        <div class="page-switch-container">
                            <button class="page-switch-btn active" onclick="switchPage('schedule')">排班表</button>
                            <button class="page-switch-btn" onclick="switchPage('leave')">请假申请</button>
                        </div>
                        
                        <!-- 排班表页面 -->
                        <div id="schedule-page" class="page-content active">
                            <div class="page-title">排班表</div>
                            <div class="report-area">
                                <!-- 筛选条件 -->
                                <div class="filter-container">
                                    <div class="filter-item">
                                        <label for="month-select">月份:</label>
                                        <select id="month-select" class="form-select form-select-sm">
                                            <option value="1">1月</option>
                                            <option value="2">2月</option>
                                            <option value="3">3月</option>
                                            <option value="4">4月</option>
                                            <option value="5">5月</option>
                                            <option value="6">6月</option>
                                            <option value="7">7月</option>
                                            <option value="8">8月</option>
                                            <option value="9">9月</option>
                                            <option value="10">10月</option>
                                            <option value="11">11月</option>
                                            <option value="12">12月</option>
                                        </select>
                                    </div>
                                    <button id="refresh-btn" class="btn-refresh">刷新</button>
                                </div>

                                <!-- 排班表 -->
                                <div class="schedule-container">
                                    <table class="schedule-table">
                                        <thead>
                                        <tr>
                                            <th>周日</th>
                                            <th>周一</th>
                                            <th>周二</th>
                                            <th>周三</th>
                                            <th>周四</th>
                                            <th>周五</th>
                                            <th>周六</th>
                                        </tr>
                                        </thead>
                                        <tbody id="calendarBody">
                                        <!-- 日历内容将通过JavaScript动态生成 -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- 请假申请页面 -->
                        <div id="leave-page" class="page-content">
                            <h1>请假申请</h1>
                            <!-- 员工信息卡片 -->
                            <div class="employee-card">
                                <div id="employee-avatar" class="employee-avatar">?</div>
                                <div class="employee-info">
                                    <div id="employee-name" class="employee-name">加载中...</div>
                                    <div class="employee-details">
                                        <div class="employee-detail-item">
                                            <span class="employee-detail-label">工号:</span>
                                            <span id="employee-job-number">加载中...</span>
                                        </div>
                                        <div class="employee-detail-item">
                                            <span class="employee-detail-label">部门:</span>
                                            <span id="employee-department">加载中...</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 请假申请表单 -->
                            <form id="leave-form" class="leave-form">
                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="leave-start-date">开始日期:</label>
                                        <input type="date" id="leave-start-date" class="form-control" required>
                                    </div>

                                    <div class="form-group">
                                        <label for="leave-end-date">结束日期:</label>
                                        <input type="date" id="leave-end-date" class="form-control" required>
                                    </div>

                                    <div class="form-group">
                                        <label for="schedule-id">请假排班:</label>
                                        <select id="schedule-id" class="form-control" required>
                                            <option value="">请选择排班</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="replacement-job-number">替班人员:</label>
                                        <select id="replacement-job-number" class="form-control" required>
                                            <option value="">请选择替班人员</option>
                                        </select>
                                    </div>

                                    <div class="form-group">
                                        <label for="leave-reason">请假原因:</label>
                                        <textarea id="leave-reason" class="form-control" required></textarea>
                                    </div>
                                </div>

                                <div class="btn-container">
                                    <button type="submit" class="btn btn-primary">提交申请</button>
                                </div>
                            </form>

                            <!-- 结果消息 -->
                            <div id="result-message" class="result-message"></div>

                            <!-- 请假记录 -->
                            <h2>请假记录</h2>
                            <table class="leave-table">
                                <thead>
                                <tr>
                                    <th>排班ID</th>
                                    <th>请假原因</th>
                                    <th>审批状态</th>
                                    <th>替班工号</th>
                                </tr>
                                </thead>
                                <tbody id="leave-table-body">
                                <!-- 请假记录将通过JavaScript动态生成 -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- 中间工作计划 -->
                    <div class="col-md-4 plan-section">
                        <div class="page-title">工作计划</div>
                        <div class="report-area">
                            <!-- 工作计划内容 - 关键容器元素 -->
                            <div id="work-plan-container">
                                <div id="work-plan" class="work-plan-cards">
                                    <!-- 无计划时显示 -->
                                    <p id="no-plan-message" style="display: block; text-align: center; padding: 50px 20px; color: #999; font-size: 14px;">
                                        <i class="fas fa-clock"></i> 暂无工作计划
                                    </p>
                                    <!-- 计划卡片容器 - 关键元素 -->
                                    <div id="plan-cards-container" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    </div>


                    <!-- 右侧消息通知 -->
                    <div class="col-md-4 notification-section">
                        <div class="page-title">消息通知</div>
                        <div class="report-area">
                            <!-- 消息类型筛选 -->
                            <div class="search-item mb-2">
                                <label class="search-label">消息类型</label>
                                <select class="form-select form-select-sm" id="messageTypeFilter">
                                    <option value="all">全部消息</option>
                                    <option value="applications">申请消息</option>
                                    <option value="complaints">投诉消息</option>
                                </select>
                            </div>
                            <!-- 消息卡片容器 -->
                            <div id="message-cards-container" style="overflow-y: auto;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
    
    <!-- 供应商申请修改模态框 -->
    <div class="ios-modal" id="applicationEditModal">
        <div class="ios-modal-content">
            <div class="ios-modal-header">
                <h3 class="ios-modal-title">修改供应商申请</h3>
            </div>
            <div class="ios-modal-body">
                <form id="applicationEditForm">
                    <input type="hidden" id="edit-application-id">
                    <div class="ios-form-group">
                        <label class="ios-form-label">供应商名称</label>
                        <input type="text" class="ios-form-control" id="edit-provider-name" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">工厂地址</label>
                        <input type="text" class="ios-form-control" id="edit-factory-address" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">负责人姓名</label>
                        <input type="text" class="ios-form-control" id="edit-manager-name" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">负责人电话</label>
                        <input type="text" class="ios-form-control" id="edit-manager-phone" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">公司类型</label>
                        <input type="text" class="ios-form-control" id="edit-company-type" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">注册资本</label>
                        <input type="number" class="ios-form-control" id="edit-registered-capital" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">员工人数</label>
                        <input type="number" class="ios-form-control" id="edit-employee-count" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">成立年份</label>
                        <input type="number" class="ios-form-control" id="edit-established-year" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">公司简介</label>
                        <textarea class="ios-form-control" id="edit-profile" rows="3" required></textarea>
                    </div>
                </form>
            </div>
            <div class="ios-modal-footer">
                <button type="button" class="ios-btn ios-btn-danger" id="delete-application-btn">取消申请</button>
                <button type="button" class="ios-btn ios-btn-primary" id="resubmit-application-btn">重新提交</button>
            </div>
        </div>
    </div>

    <!-- 供应商投诉修改模态框 -->
    <div class="ios-modal" id="complaintEditModal">
        <div class="ios-modal-content">
            <div class="ios-modal-header">
                <h3 class="ios-modal-title">修改供应商投诉</h3>
            </div>
            <div class="ios-modal-body">
                <form id="complaintEditForm">
                    <input type="hidden" id="edit-complaint-id">
                    <div class="ios-form-group">
                        <label class="ios-form-label">供应商名称</label>
                        <input type="text" class="ios-form-control" id="edit-complaint-provider-name" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">问题材料</label>
                        <input type="text" class="ios-form-control" id="edit-defective-material" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">投诉描述</label>
                        <textarea class="ios-form-control" id="edit-complaint-description" rows="3" required></textarea>
                    </div>
                </form>
            </div>
            <div class="ios-modal-footer">
                <button type="button" class="ios-btn ios-btn-danger" id="delete-complaint-btn">取消投诉</button>
                <button type="button" class="ios-btn ios-btn-primary" id="resubmit-complaint-btn">重新提交</button>
            </div>
        </div>
    </div>
    <!-- 设备报修编辑模态框 -->
    <div class="ios-modal" id="repairEditModal">
        <div class="ios-modal-content">
            <div class="ios-modal-header">
                <h3 class="ios-modal-title">修改设备报修</h3>
            </div>
            <div class="ios-modal-body">
                <form id="repairEditForm">
                    <input type="hidden" id="edit-repair-id">
                    <div class="ios-form-group">
                        <label class="ios-form-label">设备编号</label>
                        <input type="text" class="ios-form-control" id="edit-device-number" required>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">设备名称</label>
                        <input type="text" class="ios-form-control" id="edit-device-name" readonly>
                    </div>
                    <div class="ios-form-group">
                        <label class="ios-form-label">报修描述</label>
                        <textarea class="ios-form-control" id="edit-repair-desc" rows="3" required></textarea>
                    </div>
                </form>
            </div>
            <div class="ios-modal-footer">
                <button type="button" class="ios-btn ios-btn-primary" id="resubmit-repair-btn">重新提交</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentEmployee = {};
        let employeeSchedules = [];
        let departmentEmployees = [];
        
        // 页面切换功能
        function switchPage(pageType) {
            // 移除所有按钮的active类
            document.querySelectorAll('.page-switch-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // 隐藏所有页面内容
            document.querySelectorAll('.page-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 激活对应的按钮和页面
            if (pageType === 'schedule') {
                document.querySelector('.page-switch-btn[onclick="switchPage(\'schedule\')"]').classList.add('active');
                document.getElementById('schedule-page').classList.add('active');
            } else if (pageType === 'leave') {
                document.querySelector('.page-switch-btn[onclick="switchPage(\'leave\')"]').classList.add('active');
                document.getElementById('leave-page').classList.add('active');
                // 加载员工信息和请假相关数据
                loadEmployeeInfo();
                loadLeaveApplications();
            }
        }
        
        // 加载员工信息
        function loadEmployeeInfo() {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                if (userInfo) {
                    currentEmployee = userInfo;
                    document.getElementById('employee-name').textContent = userInfo.name || '未知';
                    document.getElementById('employee-job-number').textContent = userInfo.jobNumber || '未知';
                    document.getElementById('employee-department').textContent = userInfo.department || '未知';
                    
                    // 设置头像为姓名首字母
                    const firstLetter = userInfo.name ? userInfo.name.charAt(0).toUpperCase() : '?';
                    document.getElementById('employee-avatar').textContent = firstLetter;
                    
                    // 加载部门员工
                    if (userInfo.department) {
                        loadDepartmentEmployees(userInfo.department);
                    }
                }
            } catch (error) {
                console.error('加载员工信息失败:', error);
            }
        }// 获取当前登录用户信息
        async function getCurrentUser() {
            try {
                currentEmployee = JSON.parse(localStorage.getItem('userInfo'));
                if (!currentEmployee) {
                    throw new Error('未找到用户信息');
                }

                // 显示员工信息
                displayEmployeeInfo(currentEmployee);

                // 加载员工排班信息
                const startDate = document.getElementById('leave-start-date').value;
                loadEmployeeSchedule(startDate);

                // 加载部门员工
                loadDepartmentEmployees(currentEmployee.department);

                // 加载请假记录
                loadLeaveApplications();
            } catch (error) {
                console.error('获取用户信息出错:', error);
                showMessage('获取用户信息失败，请重新登录', false);
            }
        }

        // 显示员工信息
        function displayEmployeeInfo(employee) {
            document.getElementById('employee-name').textContent = employee.name || '未知';
            document.getElementById('employee-job-number').textContent = employee.jobNumber || '未知';
            document.getElementById('employee-department').textContent = employee.department || '未知';

            // 设置头像显示首字母
            const avatarElement = document.getElementById('employee-avatar');
            avatarElement.textContent = (employee.name && employee.name.charAt(0)) || '?';
        }

        // 加载员工排班信息
        async function loadEmployeeSchedule(dateStr) {
            try {
                const jobNumber = currentEmployee.jobNumber;
                
                if (!jobNumber) {
                    showMessage('无法获取员工工号，请重新登录', false);
                    return;
                }
                
                // 解析日期
                const date = new Date(dateStr);
                const year = date.getFullYear();
                const month = date.getMonth() + 1;
                
                const response = await fetch(`http://localhost:8080/api/schedules/employee/${jobNumber}/${year}/${month}`);
                if (!response.ok) {
                    throw new Error('获取排班数据失败');
                }
                
                const schedules = await response.json();
                employeeSchedules = schedules;
                
                // 更新排班选择框
                updateScheduleSelect(schedules, dateStr);
            } catch (error) {
                console.error('加载排班数据出错:', error);
                showMessage('加载排班数据失败，请稍后重试', false);
            }
        }

        // 更新排班选择框
        function updateScheduleSelect(schedules, dateStr) {
            const scheduleSelect = document.getElementById('schedule-id');
            scheduleSelect.innerHTML = '<option value="">请选择排班</option>';
            
            // 筛选当天的排班记录
            const date = new Date(dateStr);
            const daySchedules = schedules.filter(schedule => {
                const scheduleDate = new Date(schedule.scheduleTime);
                return scheduleDate.getDate() === date.getDate() &&
                       scheduleDate.getMonth() === date.getMonth() &&
                       scheduleDate.getFullYear() === date.getFullYear() &&
                       schedule.isActive;
            });
            
            if (daySchedules.length === 0) {
                const option = document.createElement('option');
                option.value = '';
                option.textContent = '当天没有排班';
                option.disabled = true;
                scheduleSelect.appendChild(option);
                return;
            }
            
            // 添加排班选项
            daySchedules.forEach(schedule => {
                const option = document.createElement('option');
                option.value = schedule.id;
                
                // 格式化时间
                const scheduleTime = new Date(schedule.scheduleTime);
                const hours = scheduleTime.getHours().toString().padStart(2, '0');
                const minutes = scheduleTime.getMinutes().toString().padStart(2, '0');
                
                option.textContent = `${schedule.department} ${hours}:${minutes}`;
                scheduleSelect.appendChild(option);
            });
        }

        // 加载部门员工
        async function loadDepartmentEmployees(department) {
            try {
                const response = await fetch('http://localhost:8080/api/persons');
                if (!response.ok) {
                    throw new Error('获取员工数据失败');
                }

                const allEmployees = await response.json();
                
                // 筛选同部门的其他员工
                departmentEmployees = allEmployees.filter(emp =>
                    emp.department === department && emp.jobNumber !== currentEmployee.jobNumber
                );
                
                // 更新替班人员选择框
                updateReplacementSelect(departmentEmployees);
            } catch (error) {
                console.error('加载员工数据出错:', error);
                showMessage('加载员工数据失败，请稍后重试', false);
            }
        }

        // 更新替班人员选择框
        function updateReplacementSelect(employees) {
            const replacementSelect = document.getElementById('replacement-job-number');
            replacementSelect.innerHTML = '<option value="">请选择替班人员</option>';
            
            if (employees.length === 0) {
                const option = document.createElement('option');
                option.value = '';
                option.textContent = '没有可选的替班人员';
                option.disabled = true;
                replacementSelect.appendChild(option);
                return;
            }
            
            // 添加员工选项
            employees.forEach(emp => {
                const option = document.createElement('option');
                option.value = emp.jobNumber;
                option.textContent = `${emp.name} (${emp.jobNumber})`;
                replacementSelect.appendChild(option);
            });
        }

        // 加载请假记录
        async function loadLeaveApplications() {
            try {
                const jobNumber = currentEmployee.jobNumber;
                
                if (!jobNumber) {
                    return;
                }
                
                // 调用后端API获取请假记录
                const response = await fetch(`http://localhost:8080/api/leaves/employee/${jobNumber}`);
                if (!response.ok) {
                    throw new Error('获取请假记录失败');
                }
                const leaveApplications = await response.json();
                // 显示请假记录
                displayLeaveApplications(leaveApplications);
            } catch (error) {
                console.error('加载请假记录出错:', error);
                showMessage('加载请假记录失败，请稍后重试', false);
            }
        }

        // 显示请假记录
        function displayLeaveApplications(applications) {
            const tableBody = document.getElementById('leave-table-body');
            tableBody.innerHTML = '';

            if (applications.length === 0) {
                const noDataRow = document.createElement('tr');
                noDataRow.innerHTML = `<td colspan="4" style="text-align: center; color: #999;">暂无请假记录</td>`;
                tableBody.appendChild(noDataRow);
                return;
            }

            // 填充表格数据
            applications.forEach(item => {
                const row = document.createElement('tr');

                // 格式化状态
                let statusText = '待审批';
                let statusClass = 'status-pending';

                if (item.isApproved === true) {
                    statusText = '已通过';
                    statusClass = 'status-approved';
                } else if (item.isApproved === false) {
                    statusText = '未通过';
                    statusClass = 'status-rejected';
                }

                row.innerHTML = `
                    <td>${item.scheduleId}</td>
                    <td>${item.description}</td>
                    <td><span class="${statusClass}">${statusText}</span></td>
                    <td>${item.substituteJobNumber}</td>
                `;

                tableBody.appendChild(row);
            });
        }

        // 格式化日期为yyyy-MM-dd格式
        function formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }

        // 处理表单提交
        async function handleSubmit(event) {
            event.preventDefault();

            // 获取表单数据
            const scheduleId = document.getElementById('schedule-id').value;
            const startDate = document.getElementById('leave-start-date').value;
            const endDate = document.getElementById('leave-end-date').value;
            const reason = document.getElementById('leave-reason').value;
            const replacementJobNumber = document.getElementById('replacement-job-number').value;

            // 表单验证
            if (!scheduleId) {
                showMessage('请选择排班', false);
                return;
            }

            if (!startDate || !endDate) {
                showMessage('请选择请假日期', false);
                return;
            }

            if (new Date(startDate) > new Date(endDate)) {
                showMessage('结束日期不能早于开始日期', false);
                return;
            }

            if (!reason) {
                showMessage('请填写请假原因', false);
                return;
            }

            if (!replacementJobNumber) {
                showMessage('请选择替班人员', false);
                return;
            }

            try {
                // 构建请假申请数据
                const leaveApplication = {
                    scheduleId: parseInt(scheduleId),
                    substituteJobNumber: currentEmployee.jobNumber,
                    startDate: startDate,
                    endDate: endDate,
                    description: reason,
                    replacementJobNumber: replacementJobNumber
                };

                // 发送请假申请
                const response = await fetch('http://localhost:8080/api/leaves/apply', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(leaveApplication)
                });

                const result = await response.json();

                if (response.ok) {
                    // 重置表单
                    document.getElementById('leave-form').reset();

                    // 重新设置日期为当前日期
                    const today = new Date();
                    const formattedDate = formatDate(today);
                    document.getElementById('leave-start-date').value = formattedDate;
                    document.getElementById('leave-end-date').value = formattedDate;

                    // 重新加载请假记录
                    loadLeaveApplications();

                    showMessage('请假申请提交成功', true);
                } else {
                    showMessage(`请假申请提交失败：${result.message}`, false);
                }
            } catch (error) {
                console.error('提交请假申请出错:', error);
                showMessage('提交请假申请失败，请稍后重试', false);
            }
        }
        
        // 显示消息
        function showMessage(message, isSuccess) {
            const messageDiv = document.getElementById('result-message');
            messageDiv.textContent = message;
            messageDiv.className = `result-message ${isSuccess ? 'success-message' : 'error-message'}`;
            messageDiv.style.display = 'block';
            
            // 3秒后隐藏消息
            setTimeout(() => {
                messageDiv.style.display = 'none';
            }, 3000);
        }
        


        document.addEventListener('DOMContentLoaded', function () {
            // 确保 DOM 加载完成后执行
            var menuItems = document.querySelectorAll('.menu-list .menu-item');

            menuItems.forEach(function (menuItem) {
                const mainLink = menuItem.querySelector(':scope > a'); // 选择直接子链接
                const submenu = menuItem.querySelector(':scope > .submenu'); // 选择直接子菜单

                if (submenu) {
                    // 如果菜单项有子菜单，在主链接上添加点击事件监听器
                    mainLink.addEventListener('click', function (e) {
                        e.preventDefault(); // 阻止子菜单父项的默认链接行为
                        // 切换父菜单项上的 active 类
                        menuItem.classList.toggle('active');
                    });
                } else {
                    // 如果是顶级菜单项且没有子菜单（例如首页）
                    mainLink.addEventListener('click', function (e) {
                        // 从所有菜单项中移除 active 类
                        document.querySelectorAll('.menu-list .menu-item').forEach(function (el) {
                            el.classList.remove('active');
                        });
                        // 为点击的菜单项添加 active 类
                        menuItem.classList.add('active');
                        // 允许默认的链接行为（页面跳转）
                    });
                }
            });

            // 处理子菜单链接的点击事件（允许默认行为）
            document.querySelectorAll('.submenu a').forEach(function(submenuLink) {
                submenuLink.addEventListener('click', function(e) {
                    // 从所有菜单项和子菜单链接中移除 active 类
                    document.querySelectorAll('.menu-list .menu-item').forEach(function (el) {
                        el.classList.remove('active');
                    });
                    document.querySelectorAll('.submenu a').forEach(function(el) {
                        el.classList.remove('active');
                    });

                    // 为父菜单项和点击的子菜单链接添加 active 类
                    const parentMenuItem = submenuLink.closest('.menu-item');
                    if (parentMenuItem) {
                        parentMenuItem.classList.add('active');
                    }
                    submenuLink.classList.add('active');
                });
            });

            // 检查当前页面路径，并在加载时高亮对应的菜单项
            const currentPath = window.location.pathname;
            document.querySelectorAll('.menu-list a').forEach(function (link) {
                if (link.getAttribute('href') && currentPath.includes(link.getAttribute('href'))) {
                    document.querySelectorAll('.menu-list .menu-item').forEach(function (el) {
                        el.classList.remove('active');
                    });
                    document.querySelectorAll('.submenu a').forEach(function(el) {
                        el.classList.remove('active');
                    });

                    const parentMenuItem = link.closest('.menu-item');
                    if (parentMenuItem) {
                        parentMenuItem.classList.add('active');
                    }
                    if (link.closest('.submenu')) {
                        link.classList.add('active');
                    }
                }
            });
            
            // 绑定请假表单提交事件
            document.getElementById('leave-form').addEventListener('submit', handleSubmit);
            
            // 绑定日期变化事件，加载对应日期的排班信息
            document.getElementById('leave-start-date').addEventListener('change', function() {
                const dateStr = this.value;
                if (dateStr) {
                    loadEmployeeSchedule(dateStr);
                }
            });
        });

        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('userInfo');
                localStorage.removeItem('token');
                window.location.href = '../../../login.html';
            }
        }

        let currentDate = new Date();
        let currentYear = currentDate.getFullYear();
        let currentMonth = currentDate.getMonth() + 1;

        // 加载排班数据
        async function loadScheduleData() {
            try {
                // 获取当前登录用户的工号
                const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                if (!userInfo || !userInfo.jobNumber) {
                    throw new Error('未找到用户信息');
                }

                const jobNumber = userInfo.jobNumber;
                const month = document.getElementById('month-select').value;

                // 更新当前年月
                currentMonth = parseInt(month);

                // 调用后端API获取指定员工的排班信息
                const response = await fetch(`http://localhost:8080/api/schedules/employee/${jobNumber}/${currentYear}/${currentMonth}`);
                if (!response.ok) {
                    throw new Error('获取排班数据失败');
                }

                const schedules = await response.json();
                displaySchedules(schedules);
            } catch (error) {
                console.error('加载排班数据出错:', error);
                alert('加载排班数据失败，请稍后重试');
            }
        }

        // 显示排班数据
        function displaySchedules(schedules) {
            const calendarBody = document.getElementById('calendarBody');
            calendarBody.innerHTML = '';

            const firstDay = new Date(currentYear, currentMonth - 1, 1);
            const lastDay = new Date(currentYear, currentMonth, 0);
            const daysInMonth = lastDay.getDate();
            const startingDay = firstDay.getDay();

            let date = 1;
            for (let i = 0; i < 6; i++) {
                const row = document.createElement('tr');

                for (let j = 0; j < 7; j++) {
                    const cell = document.createElement('td');

                    if (i === 0 && j < startingDay) {
                        cell.classList.add('empty');
                    } else if (date > daysInMonth) {
                        cell.classList.add('empty');
                    } else {
                        // 添加日期
                        const dateDiv = document.createElement('div');
                        dateDiv.classList.add('date');
                        dateDiv.textContent = date;
                        cell.appendChild(dateDiv);

                        // 添加内容容器
                        const contentDiv = document.createElement('div');
                        contentDiv.classList.add('content');

                        // 查找当天的排班记录
                        const currentDate = new Date(currentYear, currentMonth - 1, date);
                        const daySchedules = schedules.filter(schedule => {
                            const scheduleDate = new Date(schedule.scheduleTime);
                            return scheduleDate.getDate() === date &&
                                scheduleDate.getMonth() === currentMonth - 1 &&
                                scheduleDate.getFullYear() === currentYear;
                        });

                        // 显示排班信息
                        daySchedules.forEach(schedule => {
                            const scheduleDiv = document.createElement('div');
                            scheduleDiv.classList.add('schedule-entry');
                            if (!schedule.isActive) {
                                scheduleDiv.classList.add('inactive-entry');
                            }

                            // 获取班次时间并格式化显示
                            const scheduleTime = new Date(schedule.scheduleTime);
                            const hours = scheduleTime.getHours();
                            let shiftType = '';
                            if (hours >= 8 && hours < 16) {
                                shiftType = '早班';
                            } else if (hours >= 16 || hours < 0) {
                                shiftType = '中班';
                            } else {
                                shiftType = '晚班';
                            }

                            // 格式化时间，只显示小时
                            const formattedTime = `${hours}:00`;

                            scheduleDiv.innerHTML = `
                                <span class="shift-type">${shiftType}</span>
                                <span class="department">${schedule.department}</span>
                                <span class="shift-time">${formattedTime}</span>
                            `;
                            contentDiv.appendChild(scheduleDiv);
                        });

                        cell.appendChild(contentDiv);
                        date++;
                    }

                    row.appendChild(cell);
                }

                calendarBody.appendChild(row);
                if (date > daysInMonth) break;
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 设置月份选择框为当前月份
            document.getElementById('month-select').value = currentMonth;

            // 加载排班数据
            loadScheduleData();

            // 绑定筛选事件
            document.getElementById('month-select').addEventListener('change', loadScheduleData);
            document.getElementById('refresh-btn').addEventListener('click', loadScheduleData);

             // 新添加的工作计划功能
        loadWorkPlansForCurrentUser();
        });
// 加载当前用户的工作计划
function loadWorkPlansForCurrentUser() {
    let userName = '未登录';
    try {
        const userData = localStorage.getItem('userInfo');
        if (userData) {
            const user = JSON.parse(userData);
            userName = user.name || '未登录';
        }
    } catch (e) {
        console.error('获取用户信息失败:', e);
    }

    console.log("当前登录用户名:", userName);

    if (userName === '未登录' || userName === '') {
        console.log("未登录用户，不加载工作计划");
        renderEmptyPlanMessage();
        return;
    }

    // 1. 获取所有产品数据
    axios.get('http://localhost:8080/api/products')
        .then(response => {
            const allProducts = response.data;
            console.log("获取到的产品总数:", allProducts.length);

            if (!allProducts || allProducts.length === 0) {
                console.log("无产品数据，退出");
                renderEmptyPlanMessage();
                return;
            }

            // 示例产品数据结构检查
            console.log("第一个产品:", allProducts[0]);

            // 不区分大小写的匹配，增加空值检查
            const userProducts = allProducts.filter(product =>
                product.operatorName &&
                product.operatorName.toLowerCase() === userName.toLowerCase()
            );

            console.log("用户相关产品数:", userProducts.length);

            if (userProducts.length === 0) {
                console.log("当前用户无相关产品，退出");
                renderEmptyPlanMessage();
                return;
            }

            // 提取产品编码
            const productCodes = userProducts.map(p => p.productCode);
            console.log("提取的产品编码:", productCodes);

            if (productCodes.length === 0) {
                console.log("无有效产品编码，退出");
                renderEmptyPlanMessage();
                return;
            }

            // 2. 获取所有计划详情数据
            return axios.get('http://localhost:8080/api/Product_Plan_Details')
                .then(response => {
                    const allPlanDetails = response.data;
                    console.log("获取到的计划详情总数:", allPlanDetails.length);

                    if (!allPlanDetails || allPlanDetails.length === 0) {
                        console.log("无计划详情数据，退出");
                        renderEmptyPlanMessage();
                        return;
                    }

                    // 示例计划详情数据结构检查
                    console.log("第一个计划详情:", allPlanDetails[0]);

                    // 增加空值检查和类型转换
                    const userPlanDetails = allPlanDetails.filter(detail => {
                        // 确保 detail 和 detail.product_code 存在
                        if (!detail || !detail.product_code) {
                            console.warn("无效的计划详情:", detail);
                            return false;
                        }
                        return productCodes.includes(detail.product_code);
                    });

                    console.log("匹配的计划详情数:", userPlanDetails.length);

                    if (userPlanDetails.length === 0) {
                        console.log("无匹配的计划详情，退出");
                        renderEmptyPlanMessage();
                        return;
                    }

                    // 提取唯一计划ID
                    const planIds = [...new Set(userPlanDetails.map(d => d.plan_id))];
                    console.log("提取的唯一计划ID:", planIds);

                    if (planIds.length === 0) {
                        console.log("无有效计划ID，退出");
                        renderEmptyPlanMessage();
                        return;
                    }

                    // 3. 获取所有计划主表数据
                    return axios.get('http://localhost:8080/api/product_plans')
                        .then(response => {
                            const allPlans = response.data;
                            console.log("获取到的计划总数:", allPlans.length);

                            if (!allPlans || allPlans.length === 0) {
                                console.log("无计划数据，退出");
                                renderEmptyPlanMessage();
                                return;
                            }

                            // 示例计划数据结构检查
                            console.log("第一个计划:", allPlans[0]);

                            // 本地过滤出匹配计划ID的计划
                            const userPlans = allPlans.filter(plan =>
                                planIds.includes(plan.plan_id)
                            );

                            console.log("用户相关计划数:", userPlans.length);

                            if (userPlans.length === 0) {
                                console.log("无用户相关计划，退出");
                                renderEmptyPlanMessage();
                                return;
                            }

                            // 组装工作计划数据
                            const workPlans = userPlans.map(plan => {
                                const planId = plan.plan_id;
                                const details = userPlanDetails.filter(d => d.plan_id === planId);
                                const products = details.map(d => ({
                                    productCode: d.product_code,
                                    quantity: d.product_quantity
                                }));

                                return {
                                    planId,
                                    startTime: plan.start_time,
                                    endTime: plan.end_time,
                                    products
                                };
                            });

                            console.log("最终工作计划数据:", workPlans);

                            // 渲染工作计划卡片
                            renderWorkPlanCards(workPlans);
                        })
                        .catch(error => {
                            console.error('获取计划主表数据失败:', error);
                            renderEmptyPlanMessage();
                        });
                })
                .catch(error => {
                    console.error('获取计划详情数据失败:', error);
                    renderEmptyPlanMessage();
                });
        })
        .catch(error => {
            console.error('获取产品数据失败:', error);
            renderEmptyPlanMessage();
        });
}
// 渲染工作计划卡片
function renderWorkPlanCards(workPlans) {
    const container = document.getElementById('plan-cards-container');
    const noPlanMessage = document.getElementById('no-plan-message');

    // 安全校验 DOM 元素
    if (!container || !noPlanMessage) {
        console.error('未找到计划卡片容器元素');
        return;
    }

    container.innerHTML = '';

    if (workPlans.length === 0) {
        container.style.display = 'none';
        noPlanMessage.style.display = 'block';
        return;
    }

    workPlans.forEach(plan => {
        const card = document.createElement('div');
        card.className = 'work-plan-card';
        card.style.backgroundColor = '#fff';
        card.style.borderRadius = '8px';
        card.style.boxShadow = '0 2px 10px rgba(0,0,0,0.08)';
        card.style.padding = '15px';
        card.style.marginBottom = '15px';

        // 获取第一个产品（若存在）
        const firstProduct = plan.products[0] || null;
        let productHTML = '';

        if (firstProduct) {
            productHTML = `
                <div style="display: flex; justify-content: space-between; padding: 10px; background-color: #f9f9f9; border-radius: 6px; margin-bottom: 8px;">
                    <div>
                        <p style="margin: 0; font-weight: 500;">产品代码: ${firstProduct.productCode}</p>
                    </div>
                    <div style="text-align: right;">
                        <p style="margin: 0; color: #333; font-weight: 600;">${firstProduct.quantity} 件</p>
                    </div>
                </div>
            `;
        } else {
            productHTML = `
                <div style="padding: 10px; color: #999; font-size: 14px;">
                    <p>无产品任务</p>
                </div>
            `;
        }

        card.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                <div>
                    <h4 style="margin: 0 0 10px 0; color: #333;">计划编号: ${plan.planId}</h4>
                    <p style="margin: 0 0 5px 0; font-size: 14px; color: #666;">
                        <strong>时间:</strong> ${plan.startTime} - ${plan.endTime}
                    </p>
                </div>
                <span style="background-color: #e6f7ff; color: #1890ff; padding: 3px 8px; border-radius: 4px; font-size: 12px;">
                    进行中
                </span>
            </div>
            <div style="margin-top: 15px; padding-top: 10px; border-top: 1px solid #f0f0f0;">
                <h5 style="margin: 0 0 10px 0; color: #555; font-size: 16px;">产品任务</h5>
                ${productHTML}
            </div>
        `;

        container.appendChild(card);
    });

    container.style.display = 'block';
    noPlanMessage.style.display = 'none';
}
// 渲染无计划提示
function renderEmptyPlanMessage() {
    const container = document.getElementById('plan-cards-container');
    const noPlanMessage = document.getElementById('no-plan-message');

    container.style.display = 'none';
    noPlanMessage.style.display = 'block';
}


        // 获取并显示被拒绝的申请、投诉和设备报修
        async function fetchRejectedApplicationsAndComplaints() {
            try {
                // 获取当前登录用户的工号
                const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                if (!userInfo || !userInfo.jobNumber) {
                    throw new Error('未找到用户信息');
                }

                // 获取所有申请
                const applicationsResponse = await axios.get('http://localhost:8080/api/provider/application/getApplications');
                const applications = applicationsResponse.data;

                // 获取所有投诉
                const complaintsResponse = await axios.get('http://localhost:8080/api/provider/complaints/getComplaint');
                const complaints = complaintsResponse.data;

                // 获取所有设备报修
                const repairsResponse = await axios.get('http://localhost:8080/api/device/repairs/getRepair');
                const repairs = repairsResponse.data;

                // 筛选出被拒绝的申请和投诉（status=true 且 approved=false）
                const rejectedApplications = applications.filter(app =>
                    app.status === true && app.approved === false && app.applicantJobNumber === userInfo.jobNumber
                );
                const rejectedComplaints = complaints.filter(comp =>
                    comp.status === true && comp.approved === false && comp.complainantJobNumber === userInfo.jobNumber
                );
                // 筛选出被拒绝的设备报修
                const rejectedRepairs = repairs.filter(repair =>
                    repair.status === true && repair.isApproved === false && repair.applicantJobNumber === userInfo.jobNumber
                );

                const container = document.getElementById('message-cards-container');
                container.innerHTML = '';

                if (rejectedApplications.length === 0 && rejectedComplaints.length === 0 && rejectedRepairs.length === 0) {
                    container.innerHTML = '<p>暂无被拒绝的申请、投诉或设备报修。</p>';
                    return;
                }

                // 显示被拒绝的申请
                rejectedApplications.forEach(app => {
                    const card = document.createElement('div');
                    card.classList.add('message-card');
                    card.setAttribute('data-application-id', app.applicationId);
                    card.innerHTML = `
                        <div class="message-status">已拒绝</div>
                        <h5>供应商申请: ${app.providerName}</h5>
                        <p><strong>工厂地址:</strong> ${app.factoryAddress}</p>
                        <p><strong>负责人:</strong> ${app.managerName}</p>
                        <p><strong>申请编号:</strong> ${app.applicationId}</p>
                    `;
                    card.addEventListener('click', () => showApplicationEditModal(app));
                    container.appendChild(card);
                });

                // 显示被拒绝的投诉
                rejectedComplaints.forEach(complaint => {
                    const card = document.createElement('div');
                    card.classList.add('message-card');
                    card.setAttribute('data-complaint-id', complaint.complaintId);
                    card.innerHTML = `
                        <div class="message-status">已拒绝</div>
                        <h5>供应商投诉: ${complaint.providerName}</h5>
                        <p><strong>问题材料:</strong> ${complaint.defectiveMaterial}</p>
                        <p><strong>投诉编号:</strong> ${complaint.complaintId}</p>
                    `;
                    card.addEventListener('click', () => showComplaintEditModal(complaint));
                    container.appendChild(card);
                });

                // 显示被拒绝的设备报修
                rejectedRepairs.forEach(repair => {
                    const card = document.createElement('div');
                    card.classList.add('message-card');
                    card.setAttribute('data-repair-id', repair.repairId);
                    card.innerHTML = `
                        <div class="message-status">已拒绝</div>
                        <h5>设备报修: ${repair.deviceName || repair.deviceNumber}</h5>
                        <p><strong>设备编号:</strong> ${repair.deviceNumber}</p>
                        <p><strong>报修描述:</strong> ${repair.repairDesc}</p>
                        <p><strong>报修编号:</strong> ${repair.repairId}</p>
                    `;
                    card.addEventListener('click', () => showRepairEditModal(repair));
                    container.appendChild(card);
                });

            } catch (error) {
                console.error('获取被拒绝的申请、投诉和设备报修时出错:', error);
                const container = document.getElementById('message-cards-container');
                container.innerHTML = '<p>加载消息失败。</p>';
            }
        }

        // 显示申请编辑模态框
        function showApplicationEditModal(application) {
            // 填充表单数据
            document.getElementById('edit-application-id').value = application.applicationId;
            document.getElementById('edit-provider-name').value = application.providerName;
            document.getElementById('edit-factory-address').value = application.factoryAddress;
            document.getElementById('edit-manager-name').value = application.managerName;
            document.getElementById('edit-manager-phone').value = application.managerPhone;
            document.getElementById('edit-company-type').value = application.companyType;
            document.getElementById('edit-registered-capital').value = application.registeredCapital;
            document.getElementById('edit-employee-count').value = application.employeeCount;
            document.getElementById('edit-established-year').value = application.establishedYear;
            document.getElementById('edit-profile').value = application.profile;

            // 显示模态框
            const modal = document.getElementById('applicationEditModal');
            modal.classList.add('show');
            document.body.style.overflow = 'hidden'; // 防止背景滚动
        }

        // 显示投诉编辑模态框
        function showComplaintEditModal(complaint) {
            // 填充表单数据
            document.getElementById('edit-complaint-id').value = complaint.complaintId;
            document.getElementById('edit-complaint-provider-name').value = complaint.providerName;
            document.getElementById('edit-defective-material').value = complaint.defectiveMaterial;
            document.getElementById('edit-complaint-description').value = complaint.description;

            // 显示模态框
            const modal = document.getElementById('complaintEditModal');
            modal.classList.add('show');
            document.body.style.overflow = 'hidden'; // 防止背景滚动
        }

        // 关闭模态框的函数
        function closeModal(modalId) {
            const modal = document.getElementById(modalId);
            modal.classList.remove('show');
            document.body.style.overflow = ''; // 恢复背景滚动
        }

        // 点击模态框外部关闭模态框
        document.addEventListener('click', function(event) {
            const applicationModal = document.getElementById('applicationEditModal');
            const complaintModal = document.getElementById('complaintEditModal');
            const repairModal = document.getElementById('repairEditModal');

            if (event.target === applicationModal) {
                closeModal('applicationEditModal');
            } else if (event.target === complaintModal) {
                closeModal('complaintEditModal');
            } else if (event.target === repairModal) {
                closeModal('repairEditModal');
            }
        });

        // 修改重新提交申请函数
        async function resubmitApplication() {
            try {
                const applicationData = {
                    applicationId: document.getElementById('edit-application-id').value,
                    providerName: document.getElementById('edit-provider-name').value,
                    factoryAddress: document.getElementById('edit-factory-address').value,
                    managerName: document.getElementById('edit-manager-name').value,
                    managerPhone: document.getElementById('edit-manager-phone').value,
                    companyType: document.getElementById('edit-company-type').value,
                    registeredCapital: document.getElementById('edit-registered-capital').value,
                    employeeCount: document.getElementById('edit-employee-count').value,
                    establishedYear: document.getElementById('edit-established-year').value,
                    profile: document.getElementById('edit-profile').value,
                    applicantJobNumber: JSON.parse(localStorage.getItem('userInfo')).jobNumber || null,
                    status: false,
                    approved: false
                };

                const response = await axios.put('http://localhost:8080/api/provider/application/update', applicationData);

                if (response.status === 200) {
                    alert('申请已重新提交！');
                    closeModal('applicationEditModal');
                    fetchRejectedApplicationsAndComplaints();
                } else {
                    throw new Error('重新提交申请失败');
                }
            } catch (error) {
                console.error('重新提交申请时出错:', error);
                alert('重新提交申请失败！');
            }
        }

        // 修改重新提交投诉函数
        async function resubmitComplaint() {
            try {
                const complaintData = {
                    complaintId: document.getElementById('edit-complaint-id').value,
                    providerName: document.getElementById('edit-complaint-provider-name').value,
                    defectiveMaterial: document.getElementById('edit-defective-material').value,
                    description: document.getElementById('edit-complaint-description').value,
                    complainantJobNumber: JSON.parse(localStorage.getItem('userInfo')).jobNumber || null,
                    status: false,
                    approved: false
                };

                const response = await axios.put('http://localhost:8080/api/provider/complaints/update', complaintData);

                if (response.status === 200) {
                    alert('投诉已重新提交！');
                    closeModal('complaintEditModal');
                    fetchRejectedApplicationsAndComplaints();
                } else {
                    throw new Error('重新提交投诉失败');
                }
            } catch (error) {
                console.error('重新提交投诉时出错:', error);
                alert('重新提交投诉失败！');
            }
        }

        // 修改删除申请函数
        async function deleteApplication(applicationId) {
            if (confirm('确定要取消此申请吗？')) {
                try {
                    const response = await axios.delete(`http://localhost:8080/api/provider/application/delete/${applicationId}`);

                    if (response.status === 200) {
                        alert('申请已取消！');
                        closeModal('applicationEditModal');
                        fetchRejectedApplicationsAndComplaints();
                    } else {
                        throw new Error('取消申请失败');
                    }
                } catch (error) {
                    console.error('取消申请时出错:', error);
                    alert('取消申请失败！');
                }
            }
        }

        // 修改删除投诉函数
        async function deleteComplaint(complaintId) {
            if (confirm('确定要取消此投诉吗？')) {
                try {
                    const response = await axios.delete(`http://localhost:8080/api/provider/complaints/delete/${complaintId}`);

                    if (response.status === 200) {
                        alert('投诉已取消！');
                        closeModal('complaintEditModal');
                        fetchRejectedApplicationsAndComplaints();
                    } else {
                        throw new Error('取消投诉失败');
                    }
                } catch (error) {
                    console.error('取消投诉时出错:', error);
                    alert('取消投诉失败！');
                }
            }
        }

        // 显示设备报修编辑模态框
        function showRepairEditModal(repair) {
            // 填充表单数据
            document.getElementById('edit-repair-id').value = repair.repairId;
            document.getElementById('edit-device-number').value = repair.deviceNumber;
            document.getElementById('edit-device-name').value = repair.deviceName || '';
            document.getElementById('edit-repair-desc').value = repair.repairDesc;

            // 显示模态框
            const modal = document.getElementById('repairEditModal');
            modal.classList.add('show');
            document.body.style.overflow = 'hidden'; // 防止背景滚动
        }

        // 修改重新提交设备报修函数
        async function resubmitRepair() {
            try {
                const repairData = {
                    repairId: document.getElementById('edit-repair-id').value,
                    deviceNumber: document.getElementById('edit-device-number').value,
                    repairDesc: document.getElementById('edit-repair-desc').value,
                    applicantJobNumber: JSON.parse(localStorage.getItem('userInfo')).jobNumber || null,
                    status: false,
                    isApproved: false
                };

                const response = await axios.put('http://localhost:8080/api/device/repairs/update', repairData);

                if (response.status === 200) {
                    alert('设备报修已重新提交！');
                    closeModal('repairEditModal');
                    fetchRejectedApplicationsAndComplaints();
                } else {
                    throw new Error('重新提交设备报修失败');
                }
            } catch (error) {
                console.error('重新提交设备报修时出错:', error);
                alert('重新提交设备报修失败！');
            }
        }

        // 页面加载完成后绑定事件
        document.addEventListener('DOMContentLoaded', function() {
            // 获取被拒绝的申请、投诉和设备报修
            fetchRejectedApplicationsAndComplaints();

            // 绑定重新提交按钮事件
            document.getElementById('resubmit-application-btn').addEventListener('click', resubmitApplication);
            document.getElementById('resubmit-complaint-btn').addEventListener('click', resubmitComplaint);
            document.getElementById('resubmit-repair-btn').addEventListener('click', resubmitRepair);

            // 绑定删除按钮事件
            document.getElementById('delete-application-btn').addEventListener('click', function() {
                const applicationId = document.getElementById('edit-application-id').value;
                deleteApplication(applicationId);
            });
            document.getElementById('delete-complaint-btn').addEventListener('click', function() {
                const complaintId = document.getElementById('edit-complaint-id').value;
                deleteComplaint(complaintId);
            });

            // 绑定消息类型筛选事件
            document.getElementById('messageTypeFilter').addEventListener('change', function() {
                const selectedType = this.value;
                const cards = document.querySelectorAll('#message-cards-container .message-card');

                cards.forEach(card => {
                    if (selectedType === 'all') {
                        card.style.display = 'block';
                    } else if (selectedType === 'applications') {
                        card.style.display = card.hasAttribute('data-application-id') ? 'block' : 'none';
                    } else if (selectedType === 'complaints') {
                        card.style.display = card.hasAttribute('data-complaint-id') ? 'block' : 'none';
                    } else if (selectedType === 'repairs') {
                        card.style.display = card.hasAttribute('data-repair-id') ? 'block' : 'none';
                    }
                });
            });
        });
    </script>
</body>
</html>